package com.szdtoo.credentials;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;

public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher {

    private Cache<String, AtomicInteger> cache;

    public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("passwordRetryCache");
    }

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String username = (String)token.getPrincipal();
        AtomicInteger count = cache.get(username);
        if(count == null) {
            count = new AtomicInteger(0);
            cache.put(username,count);
        }
        if(count.incrementAndGet() > 5) {
            throw new ExcessiveAttemptsException();
        }
        boolean flag = super.doCredentialsMatch(token, info);
        if(flag) {
            cache.remove(username);
        }
        return flag;
    }
}
